#!/usr/bin/node

let items = [];
const log = console.log,
      http = require('http'),
      url = require('url'),
      qs = require('querystring');

function genPage(){ 
  
  let dom = items.map(i=>'<li>'+i+'</li>').join('\n');

  let html = `<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
          <title>todolist</title>
      </head>
      <body>
      <h1>TodoList</h1>
        <form method="POST" action="http://192.168.38.144:8080">
          <input type="text" name="item">
          <input type="submit" value="submit">
        </form>
        <ul id='items'>${dom}</ul>
      </body>
    </html>`;
  return html;
}

http.createServer((req,res)=>{
  let addr = url.parse(req.url);
  if(addr.pathname!=='/'){
    res.statusCode = 404;
    res.setHeader('Content-Type','text/html');
    res.end('<h1>Not Found 404</h1>');
    return ;
  }

  let data = '';
  req.on('data',chunk => data += chunk);
  req.on('end',()=>{
    let item =  qs.parse(data).item;
    if(item !== '' && typeof(item) !== 'undefined') items.push(item);
  
    res.writeHead(200, {
      'Content-Type': 'text/html',
      'Content-Lenght': Buffer.byteLength(genPage())  
    });

    res.end(genPage());
  })

}).listen(8080);

log('hello world');
